package com.stedu.service.impl;

import com.stedu.bean.Course;
import com.stedu.mapper.CourseMapper;
import com.stedu.mapper.TeacherAndStudentMapper;
import com.stedu.mapper.TeacherMapper;
import com.stedu.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private TeacherAndStudentMapper teacherAndStudentMapper;
    @Autowired
    private TeacherMapper teacherMapper;

    @Cacheable(value = "select_course", key = "'courseList'", unless = "#result==null||#result.size()==0")
    @Override
    public List<Course> selectAll() {
        return courseMapper.selectAll();
    }

    @CacheEvict(value = "select_course", key = "'courseList'")
    @Override
    public boolean insert(Course c)  {
        return courseMapper.insert(c) == 1;
    }

    @Caching(
            evict = {
                    @CacheEvict(value = "select_course", key = "'courseList'"),
                    @CacheEvict(value = "select_course", key = "#cid")
            }
    )
    @Override
    @Transactional(rollbackFor = Exception.class)//加回滚
    public boolean delete(Integer cid) {
        //通过
        Course c = courseMapper.selectByCid(cid);
        //判断课程有没有学生操作
        if (!teacherAndStudentMapper.selectSidByTid(cid).isEmpty()) {
            return false;
        } else {
            //删除操作
            teacherMapper.updateTeacher(c);
            courseMapper.delete(cid);
            return true;
        }
    }

    @Caching(
            evict = {
                    @CacheEvict(value = "select_course", key = "'courseList'"),
                    @CacheEvict(value = "select_course", key = "#c.cid")
            }
    )
    @Override
    public boolean update(Course c) {
        return courseMapper.update(c) == 1;
    }

    @Cacheable(value = "select_course", key = "#cid", unless = "#result==null")
    @Override
    public Course selectByCid(Integer cid) {
        return courseMapper.selectByCid(cid);
    }
}
